package xyz.heyaoshare.validation.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Arrays;

import static xyz.heyaoshare.exceptions.customize.ServerException.exception;

/**
 * 校验枚举值 处理器
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午10:37
 */
@Slf4j
public class InEnumValidator implements ConstraintValidator<InEnum, Integer> {

    private int[] values;
    private boolean nullable;

    @Override
    public void initialize(InEnum inEnum) {
        Class<? extends Enum<?>> value = inEnum.value();
        this.nullable = inEnum.nullable();
        try {
            Method getValueMethod = value.getMethod("getValue");
            Enum<?>[] enumConstants = value.getEnumConstants();
            values = Arrays.stream(enumConstants)
                    .map(enumInstance -> {
                        try {
                            return getValueMethod.invoke(enumInstance);
                        } catch (Exception e) {
                            log.error("该枚举没有 getValue() 方法!", e);
                            throw exception(500, "参数校验失败，请检查参数!");
                        }
                    })
                    .mapToInt(val -> (int) val) // 确保返回值是 int 类型
                    .toArray();
        } catch (NoSuchMethodException e) {
            log.error("该枚举没有 getValue() 方法!", e);
            throw exception(500, "参数校验失败，请检查参数!");
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return nullable;
        }

        for (int validValue : values) {
            if (value == validValue) {
                return true;
            }
        }
        return false;
    }
}